#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib> //stdlib.h
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>


#define N 2
#define NUM 1024

using namespace std;

//child
void Writer(int wfd)
{
    string s = "hello, i am child";
    pid_t self = getpid();
    int number = 0;

    char buffer[NUM];
    while (true)
    {
        //构建发送字符串
        buffer[0] = 0;//字符串清空，提醒别人我将这个数组当作字符串了
        snprintf(buffer, sizeof(buffer), "%s-%d-%d", s.c_str(), self, number++);
        //cout << buffer << endl;

        //发送写入父进程， system call
        write(wfd, buffer, strlen(buffer));//向文件写入不需要算C字符串结尾'\0'
        sleep(1);
    }
}


//father
void Reader(int rfd)
{
    char buffer[NUM];

    while (true)
    {
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "father get a message[" << getpid() << "]#" << buffer << endl;
            //父子对同一个资源进行访问，父子进程会协同：父进程会等子进程
        }
        // TODO
    }
}
/*
1 - buffer是用户态缓冲区，由你的程序定义（如 char buffer[1024]），属于进程内存空间。
2 - ​文件的缓冲区是内核管理的，属于操作系统层面（通常比1024大得多，但透明对用户）。

[文件数据] → 内核缓冲区 → `read()` 拷贝到 → 用户态 buffer（你的数组） >>>>>> 内核->用户

-------------------------------------------------
两个独立的进程通过操作系统完成通信>>>

child:write->操作系统内核缓冲区->father:read
用户级缓冲区buffer数组->内核->用户级buffer数组

*/


int main()
{
    int pipefd[N] = {0};
    int n = pipe(pipefd);
    if (n < 0) return 1;

    // cout << "pipefd[0]: " << pipefd[0] << ", pipefd[1]: " << pipefd[1] << endl; 

    //child --> w, father --> r

    pid_t id = fork();
    if (id < 0) return 2;
    if (id == 0)
    {
        //child
        close(pipefd[0]);

        //IPC code
        Writer(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }
    //father
    close(pipefd[1]);

    //IPC code
    Reader(pipefd[0]);

    pid_t rid = waitpid(id, nullptr, 0);//阻塞等待
    if (id < 0) return 3;

    close(pipefd[0]);
    return 0;
}





//---------------->>>>>>通信框架<<<<<<----------------
//
// int main()
// {
//     int pipefd[N] = {0};
//     int n = pipe(pipefd);
//     if (n < 0) return 1;

//     // cout << "pipefd[0]: " << pipefd[0] << ", pipefd[1]: " << pipefd[1] << endl; 

//     //child --> w, father --> r

//     pid_t id = fork();
//     if (id < 0) return 2;
//     if (id == 0)
//     {
//         //child
//         close(pipefd[0]);

//         //IPC code
//         //Writer(pipefd[1]);

//         close(pipefd[1]);
//         exit(0);
//     }
//     //father
//     close(pipefd[1]);

//     //IPC code
//     //Reader(pipefd[0]);

//     close(pipefd[0]);
//     return 0;
// }